CMAKE_MINIMUM_REQUIRED(VERSION 2.6 FATAL_ERROR)
CMAKE_POLICY(VERSION 2.6)

IF(NOT Torch_FOUND)
  FIND_PACKAGE(Torch REQUIRED)
ENDIF()

IF(NOT TH_LIBRARIES)
  SET(TH_LIBRARIES "TH")
ENDIF(NOT TH_LIBRARIES)
MESSAGE(STATUS "TH_LIBRARIES: ${TH_LIBRARIES}")

IF(NOT THNN_INSTALL_LIB_SUBDIR)
  SET(THNN_INSTALL_LIB_SUBDIR "lib" CACHE PATH "THNN install library directory")
  SET(THNN_INSTALL_INCLUDE_SUBDIR "include" CACHE PATH "THNN install include subdirectory")
ENDIF()

# Flags
# When using MSVC
IF(MSVC)
  # we want to respect the standard, and we are bored of those **** .
  ADD_DEFINITIONS(-D_CRT_SECURE_NO_DEPRECATE=1)
  ADD_DEFINITIONS(-DTH_EXPORTS)
ENDIF(MSVC)

IF (CMAKE_VERSION VERSION_LESS "3.1")
  SET(CMAKE_C_FLAGS "-std=c99 ${CMAKE_C_FLAGS}")
ELSE ()
  SET(CMAKE_C_STANDARD 99)
ENDIF ()

# OpenMP support?
SET(WITH_OPENMP ON CACHE BOOL "OpenMP support if available?")
IF (APPLE AND CMAKE_COMPILER_IS_GNUCC)
  EXEC_PROGRAM (uname ARGS -v  OUTPUT_VARIABLE DARWIN_VERSION)
  STRING (REGEX MATCH "[0-9]+" DARWIN_VERSION ${DARWIN_VERSION})
  MESSAGE (STATUS "MAC OS Darwin Version: ${DARWIN_VERSION}")
  IF (DARWIN_VERSION GREATER 9)
    SET(APPLE_OPENMP_SUCKS 1)
  ENDIF (DARWIN_VERSION GREATER 9)
  EXECUTE_PROCESS (COMMAND ${CMAKE_C_COMPILER} -dumpversion
    OUTPUT_VARIABLE GCC_VERSION)
  IF (APPLE_OPENMP_SUCKS AND GCC_VERSION VERSION_LESS 4.6.2)
    MESSAGE(STATUS "Warning: Disabling OpenMP (unstable with this version of GCC)")
    MESSAGE(STATUS " Install GCC >= 4.6.2 or change your OS to enable OpenMP")
    SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unknown-pragmas")
    SET(WITH_OPENMP OFF CACHE BOOL "OpenMP support if available?" FORCE)
  ENDIF ()
ENDIF ()

IF (WITH_OPENMP)
  FIND_PACKAGE(OpenMP)
  IF(OPENMP_FOUND)
    MESSAGE(STATUS "Compiling with OpenMP support")
    SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
    SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
    SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
  ENDIF(OPENMP_FOUND)
ENDIF (WITH_OPENMP)

LINK_DIRECTORIES("${Torch_INSTALL_LIB}")

SET(src init.c)
ADD_LIBRARY(THNN SHARED init.c)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
### Torch packages supposes libraries prefix is "lib"
SET_TARGET_PROPERTIES(THNN PROPERTIES
  PREFIX "lib"
  IMPORT_PREFIX "lib")

TARGET_LINK_LIBRARIES(THNN ${TH_LIBRARIES})

# Luarocks bug pre-14.04 prevents us from setting it for Lua-Torch
IF(THNN_SO_VERSION)
  MESSAGE(STATUS "THNN_SO_VERSION: ${THNN_SO_VERSION}")
  SET_TARGET_PROPERTIES(THNN PROPERTIES
    VERSION   ${THNN_SO_VERSION}
    SOVERSION ${THNN_SO_VERSION})
ENDIF(THNN_SO_VERSION)

INSTALL(TARGETS THNN LIBRARY DESTINATION ${THNN_INSTALL_LIB_SUBDIR})
INSTALL(FILES THNN.h DESTINATION "${THNN_INSTALL_INCLUDE_SUBDIR}/THNN")
INSTALL(FILES generic/THNN.h DESTINATION "${THNN_INSTALL_INCLUDE_SUBDIR}/THNN/generic")
